<?php

namespace Emoney\EpayBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Emoney\EpayBundle\Entity\PayementMode;
use Emoney\EpayBundle\Form\Type\PayementType;

use Emoney\EpayBundle\Entity\StorePayment;
use Emoney\EpayBundle\Form\Type\StorePaymentType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
/**
 * api de paiement venant d'autre sites
 */
use Emoney\EpayBundle\Api\CrystalMoney;

/**
 * Description of PayementController
 *
 * @author FFOZEU
 */
class PayementController extends Controller{
    //put your code here
    function newAction(Request $request) {
        $payement = new PayementMode();
        $form = $this->createForm(new PayementType(), $payement);
        
        if ($request->getMethod() == 'POST') {
            $form->bindRequest($request);

            if ($form->isValid()) {
                // perform some action, such as saving the task to the database

                return $this->redirect($this->generateUrl('EmoneyEpayBundle_homepage'));
            }
        }else{
            return $this->render('EmoneyEpayBundle:payement:create.html.twig', array(
                'form' => $form->createView(),
            ));
        }
    }
	

    /*
	*@abstract. liste des payements
	*
	*/
    function listAction(Request $request) {

        $user = $this->container->get('security.context')->getToken()->getUser();
		if (!is_object($user) ) {
                $this->get('session')->setFlash('notice', 'Vous devez être identifié pour ajouter un projet !');
				return $this->render('EmoneyEpayBundle::error.html.twig', array());
		}

        $em = $this->container->get('doctrine')->getEntityManager();
		
		$sitesList = $em->getRepository('EmoneyEpayBundle:Sitename')->findByUserId($user->getId());
		
		if($request->isXmlHttpRequest())
		{//ajax request
		  $site_id = $request->request->get('site_id');
		}
		
		if(!empty($sitesList[0]) && empty($site_id)) {
		   $site_id = $sitesList[0]->getId();
		}

		if (empty($site_id) ) {
                $this->get('session')->setFlash('notice', "Vous n'avez pas encore de projet ajouté au systéme !");
				return $this->render('EmoneyEpayBundle::error.html.twig', array());
		}		
		$payements = $em->getRepository('EmoneyEpayBundle:StorePayment')->findBySitenameId($site_id);

		/*if (!$payements = $this->get('emoney_epay.storePayement_manager')->getStorePayement(2)) {
			throw new NotFoundHttpException($this->get('translator')->trans('This desk does not exist.'));
		}*/
		if($request->isXmlHttpRequest())
		{//ajax request
			return $this->container->get('templating')->renderResponse('EmoneyEpayBundle:Payement:listhtml.html.twig',array('payements' => $payements));
		} else {
			return $this->container->get('templating')->renderResponse('EmoneyEpayBundle:Payement:list.html.twig',array('payements' => $payements,'sitesList'=>$sitesList));
		}
    }
	

    /*
	*@abstract. liste des payements
	*
	*/
    function proceedpaymentAction(Request $request) {
	
        $this->treadpayment($request);
//		if(empty($amount)) {
//		   $message = "Montant null";
//		   return $this->render('EmoneyEpayBundle::error.html.twig', array('msg'=>$message));
//		}
		
        $user = $this->container->get('security.context')->getToken()->getUser();
		$url = $this->container->get('router')->generate('EmoneyEpayBundle_proceed_payment_set2');
		return new RedirectResponse($url);
    }
	
    /*
	*@abstract. choix du mode de payement
	*
	*/
    function proceedpayment_step2Action(Request $request) {	
	
	$session = $this->get('session');
        $payement = new StorePayment();
        $payement->setMontant($session->get('amount'));
        $payement->setCmdId($session->get('cmd_id'));
       // $payement->setSitenameId($session->get('site'));
        $em = $this->container->get('doctrine')->getEntityManager();
        $site = $em->getRepository('EmoneyEpayBundle:Sitename')->find($session->get('site_id'));
            
         $payement->setSitenameId($site);
	//$payement->setMontant($session->get('site_id'));
        $user = $this->container->get('security.context')->getToken()->getUser();
        $payement->setPhone($user->getPhone());
		
        $form = $this->createForm(new StorePaymentType(), $payement);
        
        if ($request->getMethod() == 'POST') {

            $payement->setStatus(1);//encours
            $form->bindRequest($request);
            
            if ($form->isValid()) {
                $em = $this->container->get('doctrine')->getEntityManager();
                $site = $em->getRepository('EmoneyEpayBundle:Sitename')->find($session->get('site_id'));
                
                $user = $this->container->get('security.context')->getToken()->getUser();
         
                $payement->setUserId($user);
            
                $payement->setSitenameId($site);
                
                $payement->setFraisFacture(200);
                $payement->setMontantTotal($session->get('amount'));
                $payement->setDatPayment(time());
         
         
               // echo $payement->getSitenameId(); die();
                // perform some action, such as saving the task to the database
            	$em = $this->container->get('doctrine')->getEntityManager();
                $em->persist($payement);
                $em->flush();
                return $this->redirect($session->get('backurlOk'));
            }
        }else{
            return $this->render('EmoneyEpayBundle:Payement:createTmpPayement.html.twig', array(
                'form' => $form->createView(),
            ));
        }
    }

    /*
	*@abstract. get sms format
	*
	*/
    function getpaymntinstructionsAction(Request $request) {

        $user = $this->container->get('security.context')->getToken()->getUser();
		if (!is_object($user) ) {
                $this->get('session')->setFlash('notice', 'Vous devez être identifié pour ajouter un projet !');
				return $this->render('EmoneyEpayBundle::error.html.twig', array());
		}
		
        $paymentmode = $request->request->get('paymentmode');
		
        $em = $this->container->get('doctrine')->getEntityManager();
		
		$instr = $em->getRepository('EmoneyEpayBundle:PayementMode')->find($paymentmode)->getSmsFormat();
		
		return $this->container->get('templating')->renderResponse('EmoneyEpayBundle:Payement:paymentinstructions.html.twig',
		array('instructions' => $instr));

    }	

    /*
	*@abstract. enregistre
	*
	*/
    function storepaymentAction($ref,$ref,$amount,Request $request) {

        $user = $this->container->get('security.context')->getToken()->getUser();
		
		$em = $this->container->get('doctrine')->getEntityManager();
		$dated = date('Y-m-d');

        //$site_id =  $request->query->get('site');
		//$cmd_id =  $request->query->get('cde');
		//$amount_t =  $request->query->get('amount');
		//$frais =  $request->query->get('frais');
		$amount_t =  $request->query->get('name');
		$site_id =  $request->query->get('name');
		
		//$ref =  $request->query->get('ref');
		$num =  $request->query->get('num');
		$sms =  $request->query->get('text');
		
		echo $ref." _ ".$num." _ ".$sms; exit();
		
		$amount = $amount_t - $frais ;
			 
		$store_p = new StorePayment();
		$store_p->setSitenameId($site_id);
		$store_p->setCmdId($cmd_id);
		$store_p->setMontant($amount);
		$store_p->setFraisFacture($frais);
		$store_p->setMontantTotal($amount_t);
		$store_p->setDatPayment(new \DateTime($dated));
		$em->persist($store_p);
		$em->flush();
		$message = 'OK';
		//return $this->container->get('templating')->renderResponse('MyAppFilmothequeBundle:Default:index.html.twig',array('message' => $message));
    }
	
    public function treadpayment(Request $request){
        $arraydata= array();
		//var_dump($request->request);
        $arraydata['key'] = '';//$request->request->get('version');
        $arraydata['version'] = $request->request->get('version');
        $arraydata['siteUrl'] = $request->request->get('siteUrl');
        $arraydata['returnOkUrl'] = $request->request->get('returnOkUrl');
        $arraydata['returnErrorUrl'] = $request->request->get('returnErrorUrl');
        $arraydata['customerKey'] = $request->request->get('customerKey');
        $arraydata['sitename'] = $request->request->get('sitename');
        $arraydata['email'] = $request->request->get('email');
        $arraydata['transactionId'] = $request->request->get('transactionId');
        $arraydata['dateOp'] = $request->request->get('dateOp');
        $arraydata['amount'] = $request->request->get('amount');
        $arraydata['currency'] = $request->request->get('currency');
        
        //generation de la clé de hashage
        $em = $this->container->get('doctrine')->getEntityManager();
        
        $site = $em->getRepository('EmoneyEpayBundle:Sitename')->findOneBy(array('url'=>$arraydata['siteUrl'],'name'=>$arraydata['sitename']));
        
		$arraydata['key'] = sha1($site->getId().$site->getName().$site->getUrl());
        
        $apipayement = new CrystalMoney($arraydata);
        $arraydata['cryptKey'] = $request->request->get('cryptKey');
        $cryptKey = $apipayement->getCryptKey();
        
        if($cryptKey==$arraydata['cryptKey']){
            # get the session
            $session = $this->get('session');
            # store the user'name in the session
            $session->set('amount',$arraydata['amount']);
            $session->set('cmd_id',$arraydata['transactionId']);
            $session->set('site',$arraydata['siteUrl']);
            $session->set('site_id',$site->getId());
            $session->set('backurlOk',$arraydata['returnOkUrl']);
            //die();
        }else{
            //die();
        }
    }

	

}

?>
